/*
 * UIPNGImage.cpp
 */

#include "UIPNGImage.h"
#include <iostream>
#include <SDL/SDL_image.h>

UIPNGImage::UIPNGImage(float x, float y, float width, float height,
    std::string file) {
  _xpos = x;
  _ypos = y;
  _depth = 0.;
  _width = width;
  _height = height;
  _file = file;
  _tex = 0;
  initSDLImagePNGSupport();
  if (!load(file)) {
    std::cout << "Cannot load PNG image file as an OpenGL Texture : " << file
        << std::endl;
  }
}

UIPNGImage::~UIPNGImage() {
  quitSDLImagePNGSupport();
  glDeleteTextures(1, &_tex);
}

void UIPNGImage::draw() {
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  UIImage::draw();
  glDisable(GL_BLEND);
}

bool UIPNGImage::load(std::string& file) {
  SDL_Surface* image = IMG_Load(file.c_str());
  if (!image) {
    std::cout << "IMG_Load: " << IMG_GetError() << std::endl;
    return false;
  } else {
    glGenTextures(1, &_tex);
    glBindTexture(GL_TEXTURE_2D, _tex);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    SDL_LockSurface(image);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image->w, image->h, 0, GL_RGBA,
        GL_UNSIGNED_BYTE, image->pixels);
    SDL_UnlockSurface(image);

    SDL_FreeSurface(image);
    return true;
  }
}

void UIPNGImage::initSDLImagePNGSupport() {
  int flags = IMG_INIT_PNG;
  int initted = IMG_Init(flags);
  if ((initted & flags) != flags) {
    printf("IMG_Init: Failed to init required PNG support!\n");
    printf("IMG_Init: %s\n", IMG_GetError());
  }
}

void UIPNGImage::quitSDLImagePNGSupport() {
  IMG_Quit();
}
